<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<!-- 用户名 -->
		<div>
			用户名：<input type="text" id='ipt' />
		</div>
		<!-- 性别选择 -->
		<div>
			性别：
			<select name="" id='sel'>
				<option value="1">男</option>
				<option value="0">女</option>
			</select>
		</div>
		<!-- 内容展示 -->
		<div>
			内容：<textarea name="" id="con" cols="30" rows="10"></textarea>
		</div>
		<!-- 存储按钮 -->
		<div>
			<button id='btn'>存储</button>
		</div>
		<!-- 数据展示 -->
		<table border='1' cellspacing='0' cellpadding='20' id='inner'>
			<tr>
				<th>用户名</th>
				<th>性别</th>
				<th>内容</th>
			</tr>

		</table>
		<script>
			var ipt = document.getElementById('ipt')
			var sel = document.getElementById('sel')
			var con = document.getElementById('con')
			var btn = document.getElementById('btn')
			//需要循环的元素
			var inner = document.getElementById('inner')

			//初始值，多条数据容器
			var arr = []
			//绑定点击事件
			btn.addEventListener('click', setStorage, false)
			//封装存储数据
			function setStorage() {
				//存储输入框元素内容的对象
				var obj = {
					user: ipt.value,
					sex: sel.value,
					con: con.value
				}
				console.log(obj);
				//不能直接存对象，所以给它转成字符串
				var objstr = JSON.stringify(obj)
				console.log(objstr);
				//暂定储存
				arr.push(objstr);
				console.log(arr)
				//把数组转成字符串
				var arrStr = arr.join('&')
				console.log(arrStr)
				//存储
				localStorage.setItem('list', arrStr)
				//回调
				getStorageItem(arr)
			}
			//获取本地储存
			function getStorageItem(array) {
				//获取本地储存
				array = localStorage.getItem('list')
				//检测是否有list数据
				if (array != null) {
					array = [array.split('&')]
					console.log(array)
					//创建容纳元素
					var _tr = document.createElement('tr')
					_tr.innerHTML = ''
					for (var i = 0; i < array.length; i++) {
						array[i] = eval('(' + array[i] + ")")
						console.log(array)
						_tr.innerHTML += `
										<td>${array[i].user}</td>
										<td>${array[i].sex == 0 ? '女' : '男'}</td>
										<td>${array[i].con}</td>
										`

					}
					inner.appendChild(_tr)
				} else {
					array = []
				}
			}
			// getStorageItem(arr)
		</script>
	</body>
</html>